package com.checkoutcheckins.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;

public class Connection {

	public final static String BASE_URL = "http://api.foursquare.com/";

	public final static String VERSION = "v1/";

	private static HttpURLConnection getConnection(String page, Boolean json, Boolean post,
			TreeMap<String, String> parameters) throws IOException {
		StringBuffer urlBuffer = new StringBuffer();

		urlBuffer.append(BASE_URL);
		urlBuffer.append(VERSION);
		urlBuffer.append(page);
		
		if (json)
		{
			urlBuffer.append(".json");
		}

		if (parameters != null && parameters.size() > 0) {
			
			urlBuffer.append("?");
			appendParameters(parameters, urlBuffer);
		}
		
		System.out.println(urlBuffer.toString());

		URL url = new URL(urlBuffer.toString());

		HttpURLConnection request = (HttpURLConnection) url.openConnection();
		
		if (post)
		{
			request.setRequestMethod("POST");
		}

		request.setRequestProperty("User-Agent", "checkoutcheckins:1.9");

		return request;
	}

	private static void appendParameters(TreeMap<String, String> parameters,
			StringBuffer urlString) {
		for (String param : parameters.keySet()) {
			urlString.append(param);
			urlString.append("=");
			urlString.append(parameters.get(param));

			if (param != parameters.lastKey()) {
				urlString.append("&");
			}
		}
	}

	public static String parseResponse(HttpURLConnection request) throws IOException {
		
		request.getInputStream();
		request.getContentLength();

		BufferedReader in = new BufferedReader(new InputStreamReader(request
				.getInputStream(), "UTF-8"));
		String inputLine;
		StringBuffer sb = new StringBuffer();

		while ((inputLine = in.readLine()) != null)
			sb.append(inputLine);
		in.close();
		
		return sb.toString();
	}

	public static HttpURLConnection getRequest(String string, boolean json,
			TreeMap<String, String> parameters) throws IOException {
		return getConnection(string, json, false, parameters);
	}
	
	public static HttpURLConnection getPost(String string, boolean json,
			TreeMap<String, String> parameters) throws IOException {
		return getConnection(string, json, true, parameters);
	}

}
